﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Portfolio List controller
    export class PortfolioListController {

        // portfolio filter
        public portfolioFilter: PortfolioFilterDto;
        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of portfolios
        public portfolioList: PortfolioDto[];
        // total number of portfolios
        public portfolioCount: number;
        private accountId: string;
        private userId: string;
        public hasPortfolioPermision: boolean;

        private scopeDestroyed: boolean;

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private PortfolioService: PortfolioService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private $modal: Common.IModal) {

            var ctx = this;

            $scope['portfolioList'] = ctx;

            ctx.scopeDestroyed = false;
            ctx.hasPortfolioPermision = this.PortfolioService.hasPermision();
            ctx.portfolioFilter = new PortfolioFilterDto();
            ctx.portfolioFilter.isMyPortfolio = true;
            ctx.portfolioFilter.namePortfolio = "";
            ctx.portfolioFilter.isNameEqual = false;
            ctx.orderByCol = "NameLowercase";
            ctx.orderByAsc = true;

            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId =  ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();
        }
            
        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });            
        }

        // search for portfolios when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.searchPortfolio();
            });
        }

        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.searchPortfolio();
        }

        // search list of portfolios
        public searchPortfolio(): ng.IPromise<{}> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;
            

            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();

            // get portfolio items
            var promiseGet: ng.IPromise<PortfolioDto[]> = ctx.PortfolioService.getPortfolios(ctx.portfolioFilter, skip, take, [ctx.orderByCol], ctx.orderByAsc, ctx.accountId, ctx.userId);

            var portfolioListTemp: PortfolioDto[];

            //on success list portfolios
            promiseGet.then(function (lst) {
                portfolioListTemp = lst;
            });

            //get portfolios count
            var promiseCount: ng.IPromise<number> = ctx.PortfolioService.getPortfolioCount(ctx.portfolioFilter, ctx.accountId, ctx.userId);

            var portfolioCountTemp: number;

            //on success 
            promiseCount.then(function (count) {
                portfolioCountTemp = count;
            });

            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([ promiseGet, promiseCount ]);

            promiseAll
                .then(function () {
                    ctx.portfolioList = portfolioListTemp;
                    ctx.portfolioCount = portfolioCountTemp['portfolioCount'];
                    pager.setTotalItemsCount(portfolioCountTemp['portfolioCount']);
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return promiseAll;
        }
        
        // search for my portfolio
        public selectMyPortfolio() {
            var ctx = this;

            if (ctx.scopeDestroyed)
                return;

            var filter = new PortfolioFilterDto();
            filter.namePortfolio = "";
            filter.isMyPortfolio = true;
            filter.sharingStatus = 0;
            filter.isNameEqual = false;

            ctx.portfolioFilter = filter;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        // search for shared portfolio
        public selectSharedPortfolio() {
            var ctx = this;

            if (ctx.scopeDestroyed)
                return;

            var filter = new PortfolioFilterDto();
            filter.namePortfolio = "";
            filter.sharingStatus = 2;
            filter.isMyPortfolio = false;
            filter.isNameEqual = false;
            ctx.portfolioFilter = filter;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        public deletePortfolio(id): ng.IPromise<{}> {
            var ctx = this;

            if (confirm("Are you sure you want to delete the selected Portfolio?")) {

                var promiseDelete = ctx.PortfolioService.deletePortfolio(id);

                promiseDelete['finally'](function () {
                    // repopulate list
                    ctx.searchPortfolio();
                });

                //ctx.searchPortfolio();

                return promiseDelete;
            }
        }

        public setShared(item: PortfolioDto): ng.IPromise<{}> {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = 2;

            var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

            promiseUpdate['finally'](function () {
                item.sharingStatus = 2;
                ctx.searchPortfolio();
            });

            return promiseUpdate;
        }

        public setPrivate(item: PortfolioDto): ng.IPromise<{}> {
            var ctx = this;

            var portfolioSharing = new PortfolioSharingDto();
            portfolioSharing.id = item.id;
            portfolioSharing.sharingStatus = 1;

            var promiseUpdate = ctx.PortfolioService.updateStatusPortfolio(portfolioSharing);

            promiseUpdate['finally'](function () {
                item.sharingStatus = 1;
                ctx.searchPortfolio();
            });

            return promiseUpdate;
        }

        public addTaskExportPortfolio(item: PortfolioDto): void {
            var ctx = this;

            var data = {
                id: item.id,
                accountId: ctx.accountId,
                userId: ctx.userId,
                name: item.name
            }

            var promise = ctx.LongRunningTaskManagerService.runTask('Portfolio_' + item.name + "_" + moment().format("DDMMYYYY"), angular.toJson(data), 4, true, null);
        }

        public openAddPortfolioPopup = function () {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: '/Views/Portfolio/addPortfolioWithSecurities.tpl.html',
                    controller: 'PortfolioUploadController',
                    size: 'lg',
                    backdrop: false
                });

            modalInstance.result.then((out) => {
                if (out['newStatus'] == 3)
                    ctx.searchPortfolio();
            });
        };
    }

    // register controller with News Angular module
    angular.module('Sustainalytics.Portfolio').controller('PortfolioListController', function ($rootScope: ng.IScope, $scope: ng.IScope, $q: ng.IQService, $location: ng.ILocationService, PortfolioService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, LongRunningTaskManagerService, $modal: Common.IModal) {
        var ctrl = new Sustainalytics.Portfolio.PortfolioListController($rootScope, $scope, $q, $location, PortfolioService, notificationFactory, staticObjects, LongRunningTaskManagerService, $modal);
        return ctrl;
    });
} 